/**
 * ECP Web开发 通用控件.
 * Copyright(c) 2012-2020 YGSoft.Inc
 * author:biwei
 * date:2014-7-19
 */
define(["jquery","bootstrap","ecp.utils.i18n","jquery.draggable"],function($,bootstrap,locale){
    /*
     * 针对bootstrap模态对话框的二次封装。
     */
    (function($) {
        $.fn.bsDialog = function(options) {
            var defaults = {
                title: locale.Control.sDefaultTitle,//模态窗标题
                content: '', //模态窗内容
                url: '', //远程URL 
				iframeMode: {},//body内iframe
	            fade:true,//是否有动画效果
	            modalSize:"",//窗口大小模式lg 大窗口 sm 小窗口
	            showCloseButton: true, //显示关闭按钮
                width: null,//自定义窗体宽度 
	            height:null, //模态窗body高度    
	            maxHeight:null,//模态窗body最大高度 
				isTip:false, //标准的提示窗
				detailedMessage:'', //详细信息 
				isHtml:true,  //是否html片段
				offClick:true, //是否卸载自动关闭模态框事件
				multilayer: false, //允许多层嵌套窗体 
				shrinkExpand: false,//是否可收缩和展开
				showSwitchBtn : false,//显示切换最大/最小化按钮
				fullScreenMode : false, //初始化默认全屏
                otherButtons: [], //其他按钮文本，样式默认,["确定","取消"]
                otherButtonStyles: [], //其他按钮的样式，['btn-primary','btn-primary'],bootstrap按钮样式
                bootstrapModalOption: {}, //默认的bootstrap模态对话框参数
                dialogShow: function() {}, //对话框即将显示事件
                dialogShown: function() {}, //对话框已经显示事件
                dialogHide: function() {}, //对话框即将关闭
                dialogHidden: function() {}, //对话框已经关闭事件
                clickButton: function(sender, modal, index) {} //选中按钮的序号，排除关闭按钮。sender:按钮jquery对象，model:对话框jquery对象,index:按钮的顺序,otherButtons的数组下标
            };
            var options = $.extend(defaults, options);
            var modalID = '';
            var loadimg = "";
            if (options.content == '') {
                options.content = '<img id="ajax-loader" style="display:none" height="32" width="32" src="' + loadimg + '" />'+locale.Control.sLoading;
            };
            //生成一个惟一的ID
            function getModalID() {
                var d = new Date();
                var vYear = d.getFullYear();
                var vMon = d.getMonth() + 1;
                var vDay = d.getDate();
                var h = d.getHours();
                var m = d.getMinutes();
                var se = d.getSeconds();
                var sse = d.getMilliseconds();
                return 't_' + vYear + vMon + vDay + h + m + se + sse;
            }

            $.fn.extend({
                closeDialog: function(modal) {
                    var modalObj = modal;
                    modalObj.modal('hide');
                }
            });

            return this.each(function() {
                var obj = $(this);
                modalID = getModalID();

                $(this).attr("data-target", modalID);
                var tmpHtml = '<div class="colorModal modal '; //modi
                if(options.fade){
                    tmpHtml=tmpHtml +'fade';
                }
                //扩展嵌套窗体
                if(options.multilayer){
                    tmpHtml=tmpHtml + '" data-focus-on="input:first';
                }
                tmpHtml=tmpHtml
                        +'" id="{ID}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel_{ID}" '
                        +'aria-hidden="true"><div class="modal-dialog ';
                if(options.modalSize!=""){
                    tmpHtml=tmpHtml+'modal-'+options.modalSize;
                }
                //标准的提示窗宽度
                if(options.isTip){
                	options.width = "400px";
                }
                //扩展自定义宽度
                if(options.width){
                    tmpHtml = tmpHtml+ '" style="width:'+options.width+'"><div class = "modal-content">';
                } else {
                    tmpHtml = tmpHtml+ '"><div class = "modal-content">';
                }
                tmpHtml=tmpHtml
                        +'<div class="modal-header">'
                        +'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
				//显示切换最大最小化按钮
				if(options.showSwitchBtn){
					tmpHtml=tmpHtml + '<img id="showSwitchBtn_{ID}" src="/grm/ecp/webcore/themes/default/img/switch.png" style="float: right;cursor: pointer;margin-right: 15px;margin-top: 4px;">';
				}
				//是否可收缩和展开
				if(options.shrinkExpand){
					tmpHtml=tmpHtml + '<font style="float: right;margin-right: 15px; margin-top: 1px;  cursor: pointer;color: #BEB7B7;"><i id="shrinkExpand_{ID}" class="fa fa-sort-desc"></i></font>';
				}
                tmpHtml=tmpHtml +'<h4 class="modal-title" id="myModalLabel_{ID}">{title}</h4></div><div class="modal-body" '
                        +'id="body_{ID}" style="';
                //内嵌iframe无需滚动条
                if(!options.iframeMode.url){
                    tmpHtml=tmpHtml + 'overflow-y: auto;';
                }
                //body高度
                if(options.height){
                    tmpHtml=tmpHtml + "height:" +options.height +";";
                }
                //自定义max-height属性 适用于超高窗体
                if(options.maxHeight){
                    tmpHtml=tmpHtml + "max-height:" +options.maxHeight +";";
                }
                //标准的提示窗属性
                if(options.isTip){
	            	tmpHtml = tmpHtml + "min-height:77px;padding:29px 15px;";
	            }
                
                if(typeof options.iframeMode === 'object' && options.iframeMode.url !== ''){
					tmpHtml = tmpHtml +'"><iframe id="iframe_t_{ID}" src='+options.iframeMode.url+' width=100% height=100% frameborder=0></iframe></div><div class="modal-footer">'
				} else {
					tmpHtml = tmpHtml +'">{body}</div><div class="modal-footer">';
				}
                tmpHtml=tmpHtml
                        +'<img id="ajax-loader" style="display:none" height="32" width="32" src="' + loadimg + '" />{button}</div></div></div></div>';
                var buttonHtml = '<button id="closeBtn_{ID}" class="btn" data-dismiss="modal" aria-hidden="true">'+locale.Control.sClose+'</button>';
                if (!options.showCloseButton && options.otherButtons.length > 0) {
                    buttonHtml = '';
                };
                //生成按钮
                var btnClass = 'cls-' + modalID;
                for (var i = 0; i < options.otherButtons.length; i++) {
                    buttonHtml += '<button buttonIndex="' + i + '" class="' + btnClass + ' btn ' + options.otherButtonStyles[i] + '">' + options.otherButtons[i] + '</button>';
                }
                
                //扩展div或teaxarea
                if(options.isTip && options.detailedMessage !== ""){
	            	buttonHtml = '<span id="showOrHide_{ID}" style="float:left;margin-top:8px"><i class="fa fa-angle-down"></i>&nbsp;'+locale.Control.showDetail+'</span>' + buttonHtml ;
	                if(options.isHtml){
	                    buttonHtml = buttonHtml + '<div id="detailMsg_{ID}"  style="overflow: auto;min-height:100px;text-align:left;padding:8px;max-height: 400px;margin-top: 20px; display: none ; '
	                                            + 'border:1px solid #cecece;border-radius:6px;"></div> ';
	                } else {
	                    buttonHtml = buttonHtml + '<textarea id="detailMsg_{ID}" class="form-control" readonly rows="3" style="overflow:auto; max-height:400px;margin-top: 20px; display: none"></textarea>';
	                }
	            }
              
                //替换模板标记
                //bw modi 此处不能替换为options.content,先用空
                tmpHtml = tmpHtml.replace(/{title}/g, options.title).replace(/{body}/g, '').replace(/{button}/g, buttonHtml).replace(/{ID}/g,modalID);
                $(obj).append(tmpHtml);
                if(options.iframeMode.options){
                    $(obj).find('#iframe_t_'+modalID)[0].contentWindow._options = options.iframeMode.options;
                }
                //只有一个关闭按钮时
                if(options.showCloseButton && !options.otherButtons.length){
                    $("#closeBtn_"+modalID).addClass("btn-primary");
                }
                var modalObj = $('#' + modalID),
                	$window = $(window),
                	$winHeight = $window.height(),
                	$winWidth = $window.width();
                //绑定按钮事件,不包括关闭按钮
                $('.' + btnClass).click(function() {
                    var index = $(this).attr('buttonIndex');
                    options.clickButton($(this),modalObj,index,notify);
                });
                modalObj.notify = notify;
                //绑定本身的事件
                modalObj.on('show.bs.modal', function() {
                    //异步加载远程URL
                	var $mc = $('#body_' + modalID);
                    if (options.url != '') {
                        $('#ajax-loader').show();
                        $.ajax({
                            type: "get",
                            cache:true,
                            url: options.url,
                            data: "dialogModalId=" + modalID + "&ajaxloader=ajax-loader",
                            success: function(data) {
                                $('#ajax-loader').hide();
                                $mc.html(data);
                                var dh = $dialog.height();
                                if(dh  + parseFloat($dialog.css("margin-top")) > $winHeight){
                                	if(dh > $winHeight){
                                		dh = 0;
                                	}else{
                                		dh = ($winHeight - dh)/2;
                                	}
                                	$dialog.css("margin", dh + "px auto");
                                }
                                draggableFun();
                                options.callback && options.callback($mc);
                            },
                            error: function(e) {
                                $('#ajax-loader').hide();
                                $mc.html(locale.Control.sLoadError);
                            }
                        });
                    } else {
						if(!options.iframeMode.url){
							$mc.html(options.content);
							options.callback && options.callback($mc);
						}
                    }
					//初始化全屏处理
					toFullScreen();
                    options.dialogShow.call(null, modalObj);
                });
				//模态窗高宽 在触发shown.bs.modal后才能获取
				var winSize = {},
					$body = modalObj.find(".modal-body"),
					$dialog = modalObj.find(".modal-dialog"),
					$footer = modalObj.find(".modal-footer"),
					CONST = {
						//模态窗头尾高度
						HEAD_FOOT : 148,
						//模态窗body的上下margin
						MARGIN : 25
					};
                modalObj.on('shown.bs.modal', function() {
                    //只有一个关闭按钮时，处理焦点 
                    if (options.showCloseButton && !options.otherButtons.length) {
                    	$("#closeBtn_"+modalID).focus();
                    };
					winSize = {
						height :$body[0].offsetHeight - CONST.MARGIN,
						width: $body[0].offsetWidth
					};
					switchWinSize();
					shrinkExpand();
					bindShowHide();
                    options.dialogShown.call(null, modalObj);
                });
                modalObj.on('hide.bs.modal', function() {
                    options.dialogHide.call(null, modalObj);
                });
                modalObj.on('hidden.bs.modal', function() {
                    options.dialogHidden.call(null, modalObj);
                    obj.removeAttr("data-target");
                    modalObj.remove();
                });
                //禁用点击非模态窗位置关闭模态窗
				if(options.offClick){
					options.bootstrapModalOption.backdrop = 'static';
				}
                modalObj.modal(options.bootstrapModalOption);
                
                //窗口内容收缩和展开按钮事件
				function shrinkExpand(){
					//收缩和展开
					var $shrinkExpand = $("#shrinkExpand_"+modalID);
					if($shrinkExpand && $shrinkExpand.length !== 0){
						$shrinkExpand.bind("click",function(){
							var $me = $(this);
							if($me.hasClass("fa-sort-desc")){
								$me.removeClass("fa-sort-desc").addClass("fa-sort-asc");
								$me.parent().css("margin-top","-4px");
								modalObj.find(".modal-header").css("border-radius","16px");
								$body.hide();
								$footer.hide();
							}else{
								$me.removeClass("fa-sort-asc").addClass("fa-sort-desc");
								$me.parent().css("margin-top","1px");
								modalObj.find(".modal-header").css("border-radius","0px");
								$body.show();
								$footer.show();
							}
						})
					}
				}
                
				//绑定展开隐藏按钮事件（详细信息）
				function bindShowHide(){
					var $showOrHide = $("#showOrHide_"+ modalID);
					if($showOrHide && $showOrHide.length){
					    $showOrHide.bind('click', function(){
					        var $this = $(this),
					            $detailMsg = $("#detailMsg_" + modalID);
					        if(options.isTip){
					            options.isTip = false;
					            $this.empty().html('<i class="fa fa-angle-up"></i>&nbsp;'+locale.Control.hideDetail);
					            $detailMsg.css("display","block");
					            options.isHtml ? $detailMsg.html(options.detailedMessage) : $detailMsg.val(options.detailedMessage);
					        } else {
					            options.isTip = true;
								$this.empty().html('<i class="fa fa-angle-down"></i>&nbsp;'+locale.Control.showDetail);
					            $detailMsg.css("display","none");
					        }
					    })
					}
				}
				
				//自定义按钮触发事件后提示
				function notify(msg,timer){
					$(".modal-header").prepend('<div id="saveMsg" class="inner-alert">'+msg+'</div>');
					var $saveMsg = $("#saveMsg"),
						left = -($saveMsg[0].offsetWidth)/2;
					$saveMsg.css("margin-left", left);
					var startTime = new Date().getTime(),
						delayTime = timer || 5000,
						endTime,
						time =setTimeout(function(){
							$saveMsg.remove();
						},delayTime);
					$saveMsg.mouseover(function(){
						clearTimeout(time);
						endTime = new Date().getTime();
					}).mouseout(function(){
						setTimeout(function(){
							$saveMsg.remove();
							//计算剩余时间
						},delayTime - endTime + startTime);
					});
				}
				//初始化默认全屏
				function  toFullScreen() {
					if(options.fullScreenMode){
						options.draggable = false;
						options.showSwitchBtn = false;
						$dialog.css({"margin-top":0,"margin-bottom":0});
						$body.height($winHeight - CONST.HEAD_FOOT);
						$dialog.width($winWidth);
					}else{
						if($winHeight >= options.height && $winHeight >= modalObj.height()){
							modalObj.css("overflow","hidden");
						}
					}
				}
				function draggableFun(){
					//拖拽模态窗口
					var offset = modalObj.children().offset();
					var left = offset.left;
					var top = offset.top;
					modalObj.draggable({
						containment: [-left*2,-top,left*2,top],    //定义一个容器,div就只能在容器的范围内活动了
						cursor: "move",            //定义拖动时鼠标指针的状态 ，参数类型详见css中cursor配置
						//cursorAt:{top:10},         //定义拖动的时候鼠标指针的位置,此位置是相对被拖动对象的边框，单位px
						opacity: 0.80,             //设置对象被拖动时的透明度
						handle: "div.modal-header", //设置拖动控制器，也就是说当鼠标按住控制器的时候，才能拖动对象
						scroll: true,              //设置当拖动超出整个浏览器窗口,是否滚动浏览器
						distance: 20             //设置当鼠标拖动多少像素时对象才会移动
					});
					modalObj.find(".modal-header").css("cursor","move");
				}
				if(options.draggable !== false && options.url == ''){
					setTimeout(function(){
						draggableFun();
					},0)
				}
				var $switchWinSize = $("#showSwitchBtn_"+modalID);
				//浏览器窗口最大最小化重新调整模态窗
				if ($switchWinSize && $switchWinSize.length > 0 ) {
					$window.resize(function () {
						resizeForModal();
					});
				}
				//切换模态窗大小
				function  switchWinSize() {
					if ($switchWinSize && $switchWinSize.length > 0 ) {
						var winHeight = $winHeight - CONST.HEAD_FOOT,
							winWidth = $winWidth;
						//绑定按钮事件
						$switchWinSize.bind("click", function () {
							//模态窗最大化
							if(options.showSwitchBtn){
								options.showSwitchBtn = false;
								$dialog.css({"margin-top":0,"margin-bottom":0});
								$body.height(winHeight);
								$dialog.width(winWidth);
							}else{
								options.showSwitchBtn = true;
								//最小化
								$dialog.css({"margin-top":"30px","margin-bottom":"30px"});
								if(options.fullScreenMode){
									//初始化全屏显示后最小化
									 $body[0].style.height = null;
									 $dialog[0].style.width= null;
								} else {
									$body.height(winSize.height);
									$dialog.width(winSize.width);
								}
							}
						});

					}
				}
				//重置模态窗高宽
				function resizeForModal() {
					if(!options.showSwitchBtn){
						$body.height($winHeight - CONST.HEAD_FOOT);
						$dialog.width($winWidth);
						modalObj.css({"padding-left":0});
					}
				}
            });
        };
        $.extend({
            bsDialog: function(options) {
                var dom = $("body").bsDialog(options);
                return $("#"+dom.attr("data-target"))
            }
        });
    })(jQuery);
    //Window
    //基本控件扩展
    //基础输入选择类控件接口
    var Dialog={
        dialog:$.bsDialog,
        show:$.bsDialog,
        window:$.bsDialog
    }
    return  Dialog;
});